﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using MyMes.Infrastructure;
using MyMES.Dto;
using MyMES.IServices.WarehouseManagement.PhysicalStocks;
using VOL.Entity.DomainModels;

namespace MyMES.Services.WarehouseManagement.PhysicalStocks
{
    public class PhysicalStockService : IPhysicalStockService
    {
        private readonly IBaseRepository<PhysicalStock> _physicalstockRepo;
        private readonly IBaseRepository<MaterialCatalog> _materialCatalogRepo;

        public PhysicalStockService(
            IBaseRepository<PhysicalStock> physicalstockRepo,
            IBaseRepository<MaterialCatalog> materialCatalogRepo)
        {
            _physicalstockRepo = physicalstockRepo;
            _materialCatalogRepo = materialCatalogRepo;
        }

        /// <summary>
        /// 获取库存现有量列表
        /// </summary>
        /// <param name="materialCode">物料编码</param>
        /// <returns>库存列表</returns>
        public async Task<List<PhysicalStock>> GetPhysicalStockList(string materialCode)
        {
            try
            {
                // 构建查询
                var query = _physicalstockRepo.GetAll();

                // 如果提供了物料编码，添加过滤条件
                if (!string.IsNullOrWhiteSpace(materialCode))
                {
                    // 使用 StartsWith 来实现模糊匹配
                    query = query.Where(x => x.MaterialCode.StartsWith(materialCode));
                }

                // 添加排序
                query = query.OrderBy(x => x.MaterialCode);

                // 执行查询并返回结果
                var result = await query.ToListAsync();

                // 记录查询结果
                Console.WriteLine($"Found {result.Count} records for materialCode: {materialCode}");

                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"GetPhysicalStockList error: {ex.Message}");
                Console.WriteLine($"Stack trace: {ex.StackTrace}");
                throw;
            }
        }

        /// <summary>
        /// 获取物料分类树形结构
        /// </summary>
        /// <returns>分类树形结构</returns>
        public async Task<List<MaterialCatalogTreeDto>> GetMaterialCatalogTree()
        {
            try
            {
                // 1. 获取所有分类数据
                var allCategories = await _materialCatalogRepo.GetAll()
                    .OrderBy(x => x.OrderById)
                    .ToListAsync();

                // 2. 转换为DTO，安全处理可能为null的值
                var dtos = allCategories.Select(x => new MaterialCatalogTreeDto
                {
                    Id = x.Id,
                    ClassifyName = x.ClassifyName ?? "",  // 防止null
                    ParentId = x.ParentId ?? 0,          // 如果为null则设为0
                    OrderById = x.OrderById ?? 0,         // 如果为null则设为0
                    MaterialCode = x.MaterialCode ?? "",   // 防止null
                    MaterialName = x.MaterialName ?? "",   // 防止null
                    Children = new List<MaterialCatalogTreeDto>()
                }).ToList();

                // 3. 构建树形结构 - 修改根节点的查找逻辑
                var rootNodes = dtos.Where(x => x.ParentId == 0 || !dtos.Any(p => p.Id == x.ParentId)).ToList();
                foreach (var node in rootNodes)
                {
                    BuildTreeRecursive(node, dtos);
                }

                return rootNodes;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"GetMaterialCatalogTree error: {ex.Message}");
                Console.WriteLine($"Stack trace: {ex.StackTrace}");  // 添加更详细的错误日志
                throw;
            }
        }

        /// <summary>
        /// 获取所有子分类
        /// </summary>
        private List<MaterialCatalog> GetAllChildCategories(List<MaterialCatalog> allCategories, int parentId)
        {
            var result = new List<MaterialCatalog>();
            var children = allCategories.Where(x => x.ParentId == parentId);

            foreach (var child in children)
            {
                result.Add(child);
                result.AddRange(GetAllChildCategories(allCategories, child.Id));
            }

            return result;
        }

        /// <summary>
        /// 递归构建树形结构
        /// </summary>
        private void BuildTreeRecursive(MaterialCatalogTreeDto parent, List<MaterialCatalogTreeDto> allNodes)
        {
            var children = allNodes.Where(x => x.ParentId == parent.Id).ToList();
            if (children.Any())
            {
                parent.Children.AddRange(children);
                foreach (var child in children)
                {
                    BuildTreeRecursive(child, allNodes);
                }
            }
        }
    }
}